package org.jeecg.modules.zcgl.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.system.base.entity.IdBaseEntity;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.zcgl.entity.LeaseContractInfo;
import org.jeecg.modules.zcgl.enums.LeaseContractStatusEnum;
import org.jeecg.modules.zcgl.service.ILeaseContractInfoService;
import org.jeecg.modules.zcgl.vo.LeaseContractRenewVo;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 合同到期提自动结束
 */
@Slf4j
public class TerminateContractJob implements Job {

    @Autowired
    private ILeaseContractInfoService leaseContractInfoService;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) {
        long start = System.currentTimeMillis();
        log.info("定时结束合同信息开始：" + start);
        try {
            Date date = DateUtils.nextDay(-1);
            QueryWrapper<LeaseContractInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().select(IdBaseEntity::getId);
            queryWrapper.lambda().in(LeaseContractInfo::getStatus, LeaseContractStatusEnum.TAKE_EFFECT.getStatus(), LeaseContractStatusEnum.RENEW.getStatus());
            queryWrapper.apply("DATE(rent_end_time) <= DATE('" + DateUtils.formatDate(date, DateUtils.DATE_FORMAT) + "')");
            List<Object> ids = leaseContractInfoService.listObjs(queryWrapper);
            if (ids != null){
                log.info("共计：" + ids.size() + "条数据。");
                ids.stream().forEach(id -> {
                    try {
                        if (id != null && StringUtils.isNotBlank(String.valueOf(id))){
                            LeaseContractRenewVo vo = new LeaseContractRenewVo();
                            vo.setId(String.valueOf(id));
                            vo.setRent(BigDecimal.ZERO);
                            vo.setCashDeposit(BigDecimal.ZERO);
                            vo.setStatus(LeaseContractStatusEnum.TERMINATE.getStatus());
                            leaseContractInfoService.updateStatus(vo);
                        }
                    } catch (Exception e) {
                        log.error("定时结束单个合同信息失败！" + e.getMessage());
                    }
                });
            }
        } catch (Exception e) {
            log.error("定时结束合同信息失败！" + e.getMessage());
        }
        long end = System.currentTimeMillis();
        log.info("定时结束合同信息结束：" + end);
        log.info("定时结束合同信息耗时：" + (end - start) / 1000 + "S");
    }
}
